package MyFramePro.Service.Impl;

import MyFramePro.Constants.SystemConstants;
import MyFramePro.Domain.ResponseResult;
import MyFramePro.Enums.AppHttpCodeEnum;
import MyFramePro.Exception.SystemException;
import MyFramePro.Service.UploadService;
import MyFramePro.Utils.PathUtils;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.InputStream;

@Data
@Service
@ConfigurationProperties(prefix = "oss")    //指定 yml 自定义配置的前缀，将其加载，与下面的属性相关联
public class UploadServiceImpl implements UploadService {

    private String accessKey;   //属性名要和 yml 中的一致
    private String secretKey;
    private String bucket;

    /**
     * 这里是文件上传的方法
     */
    @Override
    public ResponseResult uploadImg(MultipartFile img) {

        //TODO 1.判断上传文件的类型和大小
        //1.1 获取原始的文件名
        String filename = img.getOriginalFilename();
        //1.2 判断文件的类型
        if (!(filename.endsWith(".png") || filename.endsWith(".jpg"))) {  //若不为这些类型，则给出提示信息
            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }


        //TODO 2.如果判断通过则进行上传文件的操作
        String firePath = PathUtils.generateFilePath(filename); //通过工具类创建对应文件名称的路径
        String url = myUploadOSS(img,firePath); //获取到外链名称

        return ResponseResult.okResult(url);
    }


    public String myUploadOSS(MultipartFile img,String firePath) {

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下，以文件内容的hash值作为文件名
//        String key = "2020/jzk.png";
        String key=firePath;    //这里为文件存放的目录

        try {
            InputStream inputStream = img.getInputStream(); //这里获取到流对象
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(inputStream, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);

                /**
                 *  这里 ru0fgt2s5.bkt.clouddn.com 为七牛云中的外链域名
                 */
                return "http://ru0fgt2s5.bkt.clouddn.com/" +key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        return "";
    }

}
